package com.hhss.qishi.controller.upload;

import com.hhss.qishi.config.constant.Constants;
import com.hhss.qishi.config.log.Log;
import com.hhss.qishi.entity.Annex;
import com.hhss.qishi.entity.JsonResult;
import com.hhss.qishi.service.system.AnnexService;
import com.hhss.qishi.utils.ConvertObjectUtil;
import com.hhss.qishi.utils.DateUtil;
import com.hhss.qishi.utils.FileUtil;
import com.hhss.qishi.utils.UUIDUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 附件上传控制器
 * @Author :Administrator
 * @Description
 * @Date :2019-06-04 15:53.
 */
@RestController
@RequestMapping("annex")
public class UploadAnnexController {

	@Value("${QSApplication.annex.uploadURLPath}")
	private String FILE_PATH;

	@Value("${QSApplication.annex.uploadVirtualPath}")
	private String UPLOAD_VIRTUAL_PATH;

	@Log
	Logger log;

	@Autowired
	AnnexService annexService;

	/**
	 * 接收附件上传
	 * @param file
	 * @param request
	 */
	@Transactional
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String annexUpload(MultipartFile[] file, String fkUuid, String module, HttpServletRequest request){
		JsonResult jsonResult = new JsonResult();
		if(StringUtils.isEmpty(FILE_PATH) || StringUtils.isEmpty(UPLOAD_VIRTUAL_PATH)){
			jsonResult.setResult("上传文件的路径设置不能为空");
			jsonResult.setStatus("1000022");
			return ConvertObjectUtil.toJson(jsonResult);
		}

		if(file == null){
			jsonResult.setResult("上传文件不能为空");
			jsonResult.setStatus("1000023");
			return ConvertObjectUtil.toJson(jsonResult);
		}

		if(StringUtils.isEmpty(fkUuid)){
			jsonResult.setResult("上传文件的关联fkUuid不能为空");
			jsonResult.setStatus("1000024");
			return ConvertObjectUtil.toJson(jsonResult);
		}

		// 附件所属模块 TODO
		//String module = (String)request.getQueryString();
		// 获取年月，用以储存文件
		String fileDate = DateUtil.getYYYYmm();

		Annex annex = new Annex();
		String suffix = "";	// .后缀名
		int index = -1;
		String uuids = "";	// 上传接口返回附件的uuid
		String uuid = "";
		for(MultipartFile tempFile : file){
			uuid = UUIDUtil.getUUID();
			index = tempFile.getOriginalFilename().lastIndexOf(".");
			suffix = index > 0 ? tempFile.getOriginalFilename().substring(index) : "";
			annex.setFileSuffix(suffix);
			annex.setContentType(tempFile.getContentType());
			annex.setDirectory(FILE_PATH + fileDate + "/");
			annex.setVirtualDirectory(UPLOAD_VIRTUAL_PATH + fileDate + "/");
			annex.setFileName(tempFile.getOriginalFilename());
			annex.setRealName(UUIDUtil.getUUID() + suffix);
			annex.setFileSize(tempFile.getSize() + "");
			annex.setModule(module);
			annex.setUuid(uuid);
			annex.setFkUuid(fkUuid);
			log.info("annex:" + annex.toString());
			try {
				tempFile.transferTo(FileUtil.checkDir(new File(annex.getVirtualDirectory() + annex.getRealName())));
				annexService.add(annex);
				uuids = uuid + ",";
			} catch (IOException e) {
				e.printStackTrace();
				jsonResult.setResult("上传文件失败。文件名：" + tempFile.getOriginalFilename());
				jsonResult.setStatus("1000001");
				return ConvertObjectUtil.toJson(jsonResult);
			}
		}
		if(StringUtils.endsWithIgnoreCase(uuids, ",")){
			uuids = uuids.substring(0, uuids.length() - 1);
		}
		jsonResult.setResult(uuids);
		jsonResult.setStatus("1000000");
		return ConvertObjectUtil.toJson(jsonResult);
	}

	/**
	 * 查看附件,关联外键
	 * @param fkUuid
	 */
	@RequestMapping(value = "/fkUuid/{fkUuid}", method = RequestMethod.GET)
	public List<Annex> annexViewByFkUuid(@PathVariable String fkUuid){
		Annex annex = new Annex();
		annex.setFkUuid(fkUuid);
		annex.setStatus(Constants.DB_STATUS_NORMAL);
		List<Annex> annexList = annexService.selectAllByEntity(annex);
		return annexList;
	}

	/**
	 * 获取附件的访问路径
	 * @param fkUuid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/fkUuid/address/{fkUuid}", method = RequestMethod.GET)
	public String getAnnexAddressByFkUuid(@PathVariable String fkUuid, HttpServletRequest request){
		Annex annex = new Annex();
		annex.setFkUuid(fkUuid);
		annex.setStatus(Constants.DB_STATUS_NORMAL);
		List<Annex> annexList = annexService.selectAllByEntity(annex);
		if(annexList == null){
			return "";
		}else{
			String addressStr = "";
			for(Annex an : annexList){
				addressStr += assemblyAnnexAddress(an, request) + ",";
			}
			if(StringUtils.endsWithIgnoreCase(addressStr, ",")){
				addressStr = addressStr.substring(0, addressStr.length() - 1);
			}
			return addressStr;
		}
	}


	/**
	 * 查看附件,关联uuid
	 * @param uuid
	 */
	@RequestMapping(value = "/uuid/{uuid}", method = RequestMethod.GET)
	public Annex annexView(@PathVariable String uuid){
		Annex annex = new Annex();
		annex.setUuid(uuid);
		Annex resultAnnex = annexService.getByParam(annex);
		return resultAnnex;
	}

	/**
	 * 删除附件，关联uuid
	 * @param uuid
	 */
	@RequestMapping(value = "/uuid/{uuid}", method = RequestMethod.DELETE)
	public String annexDelete(@PathVariable String uuid){
		JsonResult jsonResult = new JsonResult();
		Annex annex = new Annex();
		annex.setUuid(uuid);
		Annex resultAnnex = annexService.getByParam(annex);
		if(resultAnnex == null){
			jsonResult.setResult("数据不存在，删除错误");
			jsonResult.setStatus("1000001");
			return ConvertObjectUtil.toJson(jsonResult);
		}

		try{
			// 同步删除文件
			File file = new File(resultAnnex.getDirectory() + resultAnnex.getRealName());
			file.delete();
		}catch(Exception e){
			log.info("文件：" + resultAnnex.getDirectory() + resultAnnex.getRealName() + "删除失败！");
		}

		annexService.deleteByEntity(annex);
		jsonResult.setResult("删除成功");
		jsonResult.setStatus("1000000");
		return ConvertObjectUtil.toJson(jsonResult);
	}

	/**
	 * 根据附件实体annex装配附件的访问路径
	 * @param annex
	 * @return
	 */
	private String assemblyAnnexAddress(Annex annex, HttpServletRequest request){
		if(annex == null){
			return "";
		}
		StringBuffer url = request.getRequestURL();
		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
		String address;
		address = tempContextUrl + annex.getDirectory()+ annex.getRealName();
		return address;
	}
}
